import qs from 'qs';

interface resultMeter { [key: string]: any };

/**
 * 获取路径参数
 *
 * @param numbers 需要字符串转换为数字的
 */
export const getUrlParams = (numbers?: string[]):Record<string, any> => {
  const { search } = window.location;
  let result:resultMeter = {};
  if (search && search !== '') {
    if (search[0] === '?') {
      result = qs.parse(search.substring(1));
    }else{
      result = qs.parse(search);
    }
  }
  numbers = numbers || [];
  numbers.forEach(item => {
    if(Reflect.has(result,item)) {
      result[item] = parseInt(result[item]);
    }
  });
  return result;
};

//参数设置到路径上
export const replacePath = (params = {}) => {
  const { hash, origin, pathname } = window.location;
  const originParams = getUrlParams();//原参数
  const paramObj = { ...originParams,...params };//合并后的参数
  const search = qs.stringify(paramObj);
  const paramsUrl = search ? `?${qs.stringify(paramObj)}${hash ? hash : ''}` : `${hash ? hash : ''}`;
  const newUrl = `${origin}${pathname}${paramsUrl}`;
  // 注意,这里需要把history.state带过去,不然vue-router警告
  window.history.pushState(history.state, '', newUrl);
};

//重置路径参数
export const resetPath = () => {
  const { origin, pathname } = window.location;
  const newUrl = `${origin}${pathname}`;
  // 注意,这里需要把history.state带过去,不然vue-router警告
  window.history.pushState(history.state, '', newUrl);
};